package com.atguigu.auth.service.impl;

import com.atguigu.auth.mapper.SysRoleMapper;
import com.atguigu.auth.mapper.SysUserRoleMapper;
import com.atguigu.auth.service.SysRoleService;
import com.atguigu.auth.service.SysUserRoleService;
import com.atguigu.common.result.Result;
import com.atguigu.model.system.SysRole;
import com.atguigu.model.system.SysUserRole;
import com.atguigu.vo.system.AssignRoleVo;
import com.atguigu.vo.system.SysRoleQueryVo;
import com.atguigu.vo.system.SysRoleSaveVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
    implements SysRoleService {
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public IPage<SysRole> pageQuery(Integer current, Integer limit, SysRoleQueryVo vo) {
        Page<SysRole> pageInfo = new Page<>(current,limit);
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        if(vo != null){
            wrapper.like(!StringUtils.isEmpty(vo.getRoleName()),
                    SysRole::getRoleName, vo.getRoleName());
        }
        page(pageInfo, wrapper);
        return pageInfo;
    }

    @Override
    public Result<String> saveRole(SysRoleSaveVo saveVo) {
        SysRole role = new SysRole();
        BeanUtils.copyProperties(saveVo,role);
        if(save(role)){
            return Result.ok();
        }
        return Result.fail();
    }

    @Override
    public Result<String> updateRole(SysRoleSaveVo saveVo) {
        if(saveVo == null || saveVo.getId() == null){
            return Result.fail("传入的参数不合法");
        }
        SysRole role = getById(saveVo.getId());
        if(role == null){
            return Result.fail("要更新的角色不存在");
        }
        BeanUtils.copyProperties(saveVo,role);
        if(updateById(role)){
            return Result.ok();
        }
        return Result.fail("更新失败");
    }

    /**
     * 根据用户id查询用户对应的所有角色
     * @param userId
     * @return
     */
    @Override
    public Map<String,Object> getRoleByUserId(Long userId) {
        List<SysRole> allRoles = list();
        List<Long> roleIds = sysUserRoleMapper.getRoleIdsByUserId(userId);
        List<SysRole> roles = new ArrayList<>();
        for(SysRole role : allRoles){
            if(roleIds.contains(role.getId())){
                roles.add(role);
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("assginRoleList",roles);
        map.put("allRolesList",allRoles);
        return map;
    }

    /**
     * 为用户绑定角色
     * @param vo
     */
    @Transactional
    @Override
    public void doAssign(AssignRoleVo vo) {
        //先删除当前用户所有的角色关系
        List<Long> roleIds = vo.getRoleIdList();
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,vo.getUserId()));
        //然后再将新的角色添加到关系表中
        List<SysUserRole> sys = roleIds.stream().map(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(vo.getUserId());
            return sysUserRole;
        }).collect(Collectors.toList());
        sysUserRoleService.saveBatch(sys);
    }
}
